package snippet.kaazing;


import java.io.IOException;
import java.io.InputStream;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.kaazing.gateway.client.security.BasicChallengeHandler;
import com.kaazing.gateway.client.security.ChallengeHandlers;
import com.kaazing.gateway.client.security.LoginHandler;
import com.kaazing.gateway.jms.client.demo.JmsFrame;
import com.kaazing.gateway.jms.client.stomp.StompConnectionFactory;
import com.kaazing.gateway.jms.client.stomp.StompInitialContext;


public class SWTTableWebSockets implements MessageListener
{
	private static Context jndiInitialContext;
	private static ConnectionFactory connectionFactory;
	private static Connection connection; // JMS Connection

	private static Session session; // JMS Session
	private static Session transactedSession; // JMS Transacted Session
	private static int messageCount = 0;
	static Display display = new Display();
	static Shell shell = new Shell(display);
	static Table table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);

	String destinationName = "/topic/shiv.websocket.topic";

	//	String destinationName ="/topic/mercury.TA.TickerNotification.topic";
	public void onMessage(final Message message)
	{
		if (message instanceof TextMessage)
		{
			try
			{
				System.out.println("RECEIVED TextMessage: " + ((TextMessage) message).getText());
				Display.getDefault().asyncExec(new Runnable()
				{
					public void run()
					{
						final TableItem item = new TableItem(table, SWT.NONE);
						try
						{
							item.setText(0, "Kaazzing " + ((TextMessage) message).getText());
							item.setText(1, new Integer(table.getItems().length).toString());
							table.setSelection(table.getItems().length);
							shell.setText(destinationName + " ,Total Rows " + table.getItems().length);

						}
						catch (final JMSException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				//				message.acknowledge();

			}
			catch (final JMSException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static void initLoginHandler(final String location)
	{
		final LoginHandler loginHandler = new LoginHandler()
		{
			private String username;
			private String password;

			@Override
			public PasswordAuthentication getCredentials()
			{
				username = "admin";
				password = "sap13nt";
				return new PasswordAuthentication(username, password.toCharArray());
			}
		};
		final BasicChallengeHandler challengeHandler = ChallengeHandlers.load(BasicChallengeHandler.class);
		challengeHandler.setLoginHandler(loginHandler);
		ChallengeHandlers.setDefault(challengeHandler);
	}

	public static void main(final String[] args)
	{

		final SWTTableWebSockets sw = new SWTTableWebSockets();
		sw.initWebsocket();



		shell.setLayout(new GridLayout());


		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		final GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		table.setLayoutData(data);

		final String[] titles =
		{ "Message Number", "Count" };
		for (int i = 0; i < titles.length; i++)
		{
			final TableColumn column = new TableColumn(table, SWT.NONE);
			column.setText(titles[i]);
			if (i == 0)
			{
				column.setWidth(400);
			}
			table.getColumn(i).pack();
		}


		for (int i = 0; i < titles.length; i++)
		{
			table.getColumn(i).pack();
		}
		shell.pack();
		shell.open();

		while (!shell.isDisposed())
		{
			if (!display.readAndDispatch())
			{
				display.sleep();
			}
		}
	}

	private void initWebsocket()
	{
		try
		{
			// delegate initial context environment values to properties file
			final Properties env = new Properties();
			InputStream is = null;
			try
			{
				is = JmsFrame.class.getResourceAsStream("/jms.properties");
				env.load(is);
			}
			catch (final IOException ioe)
			{
				ioe.printStackTrace();
			}
			finally
			{
				if (is != null)
				{
					try
					{
						is.close();
					}
					catch (final IOException e)
					{
						e.printStackTrace();
					}
				}
			}
			jndiInitialContext = new InitialContext(env);
			env.put(StompInitialContext.CONNECTION_TIMEOUT, "15000");
			connectionFactory = (ConnectionFactory) jndiInitialContext.lookup("ConnectionFactory");
			System.out.println("JNDI initialization complete");
			final String url = "ws://localhost:8001/jms";
			//			String url = "ws://ldgrpmeremsl101.ladsys.net:7222/jms";

			// initialize the login handler for the target location
			initLoginHandler(url);

			final String username0 = "admin";
			final String password0 = "sap13nt";

			if (connectionFactory instanceof StompConnectionFactory)
			{
				try
				{
					((StompConnectionFactory) connectionFactory).setGatewayLocation(new URI(url));
					connection = connectionFactory.createConnection(username0, password0);
					session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
					connection.start();
					System.out.println("CONNECTED");

					//String durableSubscriberName = durableName.getText();
					//boolean hasDurableSubscriberName = (durableSubscriberName != null && !durableSubscriberName.isEmpty());
					System.out.println("SUBSCRIBE: " + destinationName);

					final Destination destination = (Destination) jndiInitialContext.lookup(destinationName);
					MessageConsumer consumer;

					consumer = session.createConsumer(destination);
					consumer.setMessageListener(this);


				}
				catch (final URISyntaxException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (final JMSException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}


		}
		catch (final NamingException e)
		{
			e.printStackTrace();
		}
	}
}
